// Overall viewmodel for this screen, along with initial state
function NoseyViewModel() {
    var self = this;
    self.sections = ko.observableArray([new Section({name: 'New Section', weight: 0})]);
    self.deletedSections = ko.observableArray();
    self.createdFields = ko.observableArray();
    self.selectedSection = ko.observable();

    // Operations
    self.updateSectionPosition = function() {
        var i = 0;
        ko.utils.arrayForEach(self.sections(), function(section) {
            section.weight(i++);
        });
    }
    self.addSection = function() {
        self.sections.push(new Section({name: 'New Section'}));
        self.updateSectionPosition();
    }
    self.removeSection = function(section) {
        bootbox.confirm(Yii.t('noseyModule.app', 'Do you really want to delete this section?'), function(confirmed) {
            if (confirmed)
            {
                self.sections.remove(section);
                if (section.id)
                    self.deletedSections.push(section);
                self.updateSectionPosition();
            }
        })
    }
    self.selectSection = function(section) {
        self.selectedSection(section);
        $('#show-preloaded-fields').trigger('click');
    }
    self.addPreloadedField = function(field) {
        $.fancybox.close();
        self.selectedSection().fields.push(field);
        self.selectedSection().updateFieldPosition();
        ocultarRating();
    }

    // Load initial state from server, convert it to Sections instances, then populate self.sections
    if ($('#Form_ko_data').val()) {
        var ko_data = $.parseJSON($('#Form_ko_data').val());
        self.sections($.map(ko_data['sections'], function(item) {
            var section = new Section(item);
            section.fields($.map(item.fields, function(item) {
                var field = new Field(item);
                field.fieldOptions($.map(item.fieldOptions, function(item) {
                    return new Option(item);
                }));
                return field;
            }));
            return section;
        }));
    }

    // Load available fields to load
    if ($('#created_fields').val()) {
        var created_fields = $.parseJSON($('#created_fields').val());
        self.createdFields($.map(created_fields, function(item) {
            var field = new Field(item);
            field.fieldOptions($.map(item.fieldOptions, function(item) {
                return new Option(item);
            }));
            return field;
        }));
    }
}